package com.ruoyi.mes.utils;

import  java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.*;
import java.nio.charset.StandardCharsets;

/**
 * Agv小车工具类
 * @author coderChen
 */
public class AgvUtils {

    private static final String BASE_URL = "http://192.168.1.100:5000/mes/agv-car";

    /**
     * 发送指令到Avg小车
     * @param action 动作指令，如 "advance" 或 "back_home"
     */
    public static void sendCommand(String action) {
        // 请求数据
        String requestData = "{\"action\":\"" + action + "\"}";

        try {
            // 创建URL对象
            URL apiUrl = new URL(BASE_URL);
            // 打开URL连接
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            // 设置请求头部信息
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 允许输出流写入数据
            connection.setDoOutput(true);
            // 将请求数据写入输出流
            try(OutputStream os = connection.getOutputStream()) {
                os.write(requestData.getBytes(StandardCharsets.UTF_8));
            }
            // 发送HTTP请求
            connection.connect();

            // 读取响应数据
            try(BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                // 打印响应
                System.out.println("Response: " + response.toString());
            }

            // 关闭连接
            connection.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 派遣Avg小车前进
     */
    public static void dispatchAgv() {
        sendCommand("advance");
    }

    /**
     * 派遣Avg小车返回停靠点1
     */
    public static void returnToDock() {
        sendCommand("back_home");
    }
}
